package org.tio.sitexxx.web.server.utils;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.session.HttpSession;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.model.main.UserToken;
import org.tio.sitexxx.service.service.base.UserRoleService;
import org.tio.sitexxx.service.service.base.UserService;
import org.tio.sitexxx.service.service.base.UserTokenService;
import org.tio.sitexxx.service.vo.RequestExt;
import org.tio.sitexxx.service.vo.RequestKey;
import org.tio.sitexxx.service.vo.SessionExt;
import org.tio.sitexxx.service.vo.SessionKey;
import org.tio.sitexxx.web.server.init.WebApiInit;

import cn.hutool.core.util.StrUtil;

/**
 * @author tanyaowu
 * 2016年8月10日 上午10:59:58
 */
public class WebUtils {
	@SuppressWarnings("unused")
	private static Logger		log			= LoggerFactory.getLogger(WebUtils.class);
	private static UserService	userService	= UserService.ME;

	/**
	 * 手动把某人登出
	 * @param uid 用户id
	 */
	public static void logout(Integer uid) {
		List<UserToken> list = UserTokenService.me.find(uid);
		if (list != null && list.size() > 0) {
			for (UserToken userToken : list) {
				String token = userToken.getToken();
				if (StrUtil.isNotBlank(token)) {
					HttpSession session = (HttpSession) WebApiInit.httpConfig.getSessionStore().get(token);

					if (session != null) {
						SessionExt sessionExt = session.getAttribute(SessionKey.SESSION_EXT, SessionExt.class, null, WebApiInit.httpConfig);
						if (sessionExt != null) {
							if (sessionExt.getUid() != null) {
								sessionExt.setUid(null);
								session.update(WebApiInit.httpConfig);//切记：每次修改SessionExt后，要调用一下update把数据更新到分布式缓存中
							}
						}
					}
				}
			}

			UserTokenService.me.delete(uid);
		}
	}

	/**
	 * 把"/user/curr"这样的path变成"/api/user/curr.php"
	 * 把"/user/curr?name=tan"这样的path变成"/api/user/curr.php?name=tan"
	 * @param path
	 * @return
	 */
	public static String path(String path) {
		String contextpath = org.tio.sitexxx.service.vo.Const.API_CONTEXTPATH;
		String suffix = org.tio.sitexxx.service.vo.Const.API_SUFFIX;

		int x = StringUtils.indexOf(path, "?");
		if (x == -1) {
			return contextpath + path + suffix;
		} else {
			String path1 = path.substring(0, x);
			String queryStr = path.substring(x + 1, path.length());
			return contextpath + path1 + suffix + "?" + queryStr;
		}
	}

	/**
	 * 获取当前用户
	 * @param session
	 * @return
	 * @author tanyaowu
	 */
	public static User currUser(HttpRequest request) {
		Integer userid = currUserId(request);
		if (userid != null) {
			User user = userService.getById(userid);
			return UserRoleService.checkUserStatus(user) ? user : null;
		}
		return null;
	}

	/**
	 * 获取当前用户的userid
	 * @param request
	 * @return
	 */
	public static Integer currUserId(HttpRequest request) {
		HttpSession session = request.getHttpSession();
		SessionExt sessionExt = session.getAttribute(SessionKey.SESSION_EXT, SessionExt.class);
		Integer userid = sessionExt.getUid();//(Integer) request.getHttpSession().getAttribute(SessionKey.CURR_USERID, Integer.class);
		return userid;
	}

	/**
	 * 根据HttpSession对象获取当前用户的userid
	 * @param session
	 * @return
	 */
	public static Integer getUserIdBySession(HttpSession session) {
		if (session == null) {
			return null;
		}
		SessionExt sessionExt = session.getAttribute(SessionKey.SESSION_EXT, SessionExt.class);
		Integer userid = sessionExt.getUid();//(Integer) request.getHttpSession().getAttribute(SessionKey.CURR_USERID, Integer.class);
		return userid;
	}

	/**
	 * RequestExt对象是个非常有用的对象
	 * @param request
	 * @return
	 */
	public static RequestExt getRequestExt(HttpRequest request) {
		return (RequestExt) request.getAttribute(RequestKey.REQUEST_EXT);
	}

	/**
	 * 获取IM服务器的端口
	 * @param request
	 * @return
	 * @author: tanyaowu
	 */
	public static int getImServerPort(HttpRequest request) {
		RequestExt requestExt = WebUtils.getRequestExt(request);
		if (requestExt.isFromBrowser()) {
			return org.tio.sitexxx.service.vo.Const.ImPort.WS;
		} else {
			return org.tio.sitexxx.service.vo.Const.ImPort.APP;
		}
	}
}
